package com.meirengu.webview.service.impl;

import com.meirengu.common.RedisClient;
import com.meirengu.service.impl.BaseServiceImpl;
import com.meirengu.webview.dao.KwInterfaceConfigDao;
import com.meirengu.webview.model.KwAreaLimit;
import com.meirengu.webview.model.KwInterfaceConfig;
import com.meirengu.webview.service.KwAreaLimitService;
import com.meirengu.webview.service.KwInterfaceConfigService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * KwInterfaceConfig服务实现层
 *
 * @author Mao
 * @create Fri Mar 30 09:50:05 CST 2018
 */
@Service
public class KwInterfaceConfigServiceImpl extends BaseServiceImpl<KwInterfaceConfig> implements KwInterfaceConfigService {

    @Autowired
    KwInterfaceConfigDao kwInterfaceConfigDao;
    @Autowired
    RedisClient redisClient;
    @Autowired
    KwAreaLimitService kwAreaLimitService;

    /**
     * 通过code查询接口配置
     *
     * @param code
     * @return
     */
    public KwInterfaceConfig findByCode(String code) {
        return kwInterfaceConfigDao.findByCode(code);
    }

    @Override
    public List<KwInterfaceConfig> getModel(Map map) throws Exception {
        return kwInterfaceConfigDao.getModel(map);
    }

    /**
     * 还原限制数量
     *
     * @throws Exception
     */
    public void restore() throws Exception {
        Map<String, String> paramsMap = new HashMap<>();
        List<KwInterfaceConfig> inList = kwInterfaceConfigDao.getModel(paramsMap);
        if (inList != null && inList.size() > 0) {
            for (KwInterfaceConfig in : inList) {
                /*当天是否已超过限制数量 isoutlimit*/
                redisClient.set("iol-" + in.getInterfaceCode(), "N");
                /*是否限制数量 islimitnum*/
                String isLimitNum = in.getLimitNum();
                redisClient.set("iln-" + in.getInterfaceCode(), isLimitNum);
                if ("Y".equals(isLimitNum)) {
                    redisClient.set("limit-num-" + in.getInterfaceCode(), in.getNum().toString());
                }
            }
        }

        Map<String, String> limitMap = new HashMap<>();
        List<KwAreaLimit> list = kwAreaLimitService.getModel(limitMap);
        if (list != null && list.size() > 0) {
            for (KwAreaLimit kwAreaLimit : list) {
                redisClient.hset("ald-" + kwAreaLimit.getChannelCode(), "out_limit_" + kwAreaLimit.getAreaCode(), "N");
                String isLimitNum = kwAreaLimit.getAreaLimit();
                redisClient.hset("ald-" + kwAreaLimit.getChannelCode(), "area_limit_" + kwAreaLimit.getAreaCode(), isLimitNum);
                if ("Y".equals(isLimitNum)) {
                    redisClient.hset("ald-" + kwAreaLimit.getChannelCode(), "limit_num_" + kwAreaLimit.getAreaCode(), kwAreaLimit.getNum().toString());
                }
            }
        }
    }
}
